/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.ez2find.backing;

import com.ez2find.manager.AreaManagerLocal;
import com.ez2find.manager.ServiceCategorieManagerLocal;
import com.ez2find.manager.ServiceManagerLocal;
import com.ez2find.manager.LocationManagerLocal;
import com.ez2find.manager.RegisterUserManagerLocal;
import com.ez2find.model.Area;
import com.ez2find.model.Service;
import com.ez2find.model.CategoriaServicio;
import com.ez2find.model.Location;
import com.ez2find.model.RegisterUser;
import com.ez2find.services.EmailLocal;
import com.ez2find.util.RequestContext;
import com.ez2find.util.SessionContext;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Administrador
 */
public class ServiceBean {

    @EJB
    private ServiceManagerLocal ejbServiceManager;
    @EJB
    private ServiceCategorieManagerLocal ejbServiceCategorieManager;
    @EJB
    private RegisterUserManagerLocal ejbUserManager;
    @EJB
    private EmailLocal ejbEmail;
    @EJB
    private AreaManagerLocal ejbAreaManager;
    @EJB
    private LocationManagerLocal ejbLocationManager;
    private Service service;
    private int back;
    private long serviceCategorieId;
    private long areaId;
    private String email1;
    private boolean linkRPOk;
    private boolean createOk;
    private boolean maskedEmail;
    private int page;
    private String searchValue;
    private boolean onlySearchTitles;
    private boolean hasImage;
    
    public Service getService() {
        if(service==null){
            ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
            HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
            HttpSession session = request.getSession();
            if (session.isNew()) {
                try {
                    String errorPageURL = externalContext.getRequestContextPath() + "/faces/welcome.jsp";
                    externalContext.redirect(errorPageURL);
                    FacesMessage msg = new FacesMessage("The session has bean expired");
                    msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                    return null;
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                    return null;
                }
            } else {
            SessionBean sessionBean=(SessionBean) SessionContext.getAttribute("sessionBean");
            if(sessionBean.getEjbSession().getService()!=null){
                service = sessionBean.getEjbSession().getService();
                if(service.getTypeReplyTo().equals("masked email"))
                    maskedEmail=true;
                areaId=0;
                if(service.getArea()!=null)
                    areaId=service.getArea().getId();
                serviceCategorieId=service.getServiceCategorie().getId();
            }
            else{
                service=new Service();
                service.setTypeReplyTo("masked email");
                if(!sessionBean.getAreasCurrentSite().isEmpty()){
                    if(sessionBean.getEjbSession().getCurrentArea()!=null)
                        areaId=sessionBean.getEjbSession().getCurrentArea().getId();
                    else
                        areaId = sessionBean.getEjbSession().getCurrentSite().getAreas().get(1).getId();
                }
                try{
                    PostBean postBean=(PostBean) RequestContext.getAttribute("postBean");
                    back=postBean.getBack();
                }catch(Exception ex){}
            }
            }
        }
        return service;
    }

    public void setService(Service service) {
        this.service = service;
    }

    public List<Service> getlistAll(){
        return ejbServiceManager.listAll();
    }
    
    public String create(){
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
        HttpSession session = request.getSession();
        if (session.isNew()) {
          try {
            String errorPageURL = externalContext.getRequestContextPath() + "/faces/servicePosting/create.jsp";
            externalContext.redirect(errorPageURL);
            FacesMessage msg = new FacesMessage("The session has bean expired");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return null;
          } catch(IOException ioe) {
            ioe.printStackTrace();
            return null;
          }
        } else {
        try {
            SessionBean sessionBean=(SessionBean) SessionContext.getAttribute("sessionBean");
            if(sessionBean.getEjbSession().getOwner()!=null){
                service.setCode((ejbServiceManager.lastCode())+1);
                service.setType("service");
                service.setUser(sessionBean.getEjbSession().getOwner());
                service.setEmail(sessionBean.getEjbSession().getOwner().getEmail());
                if(service.getTypeReplyTo().equals("masked email"))
                    ejbEmail.addAnonymousEmail("service", service.getCode(), service.getEmail());
                service.setPublishDate(new Date(System.currentTimeMillis()));
                service.setStatus("active");
                service.setCreateDate(new Date(System.currentTimeMillis()));
                service.setSite(sessionBean.getEjbSession().getCurrentSite());
                if(areaId!=0)
                    service.setArea(ejbAreaManager.find(areaId));
                CategoriaServicio serviceCategorie=ejbServiceCategorieManager.find(serviceCategorieId);
                service.setServiceCategorie(serviceCategorie);
                service.setCategorie(serviceCategorie.getCategorie());
                ejbServiceManager.create(service);
                FacesMessage msg = new FacesMessage("Your post has been successfully registered.");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                FacesMessage msg1 = new FacesMessage("To manage your post,  log into your account.");
                FacesContext.getCurrentInstance().addMessage(null, msg1);
                createOk=true;
                return "success";
            }
            else{
                if ((service.getEmail().length() < 4) || !service.getEmail().contains("@") || !service.getEmail().contains(".") || (email1.length() < 4) || !email1.contains("@") || !email1.contains(".") || !service.getEmail().equals(email1)) {
                    FacesMessage msg = new FacesMessage("The emails address don't equals or invalids");
                    msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                    return null;
                }
                RegisterUser userAccount=ejbUserManager.findUserByEmail(service.getEmail());
                if(userAccount!=null){
                    if(userAccount.getStatus().equals("active") || userAccount.getStatus().equals("reactive")){
                        service.setUser(userAccount);
                        service.setCode((ejbServiceManager.lastCode())+1);
                        service.setType("service");
                        service.setStatus("pending");
                        service.setCreateDate(new Date(System.currentTimeMillis()));
                        service.setSite(sessionBean.getEjbSession().getCurrentSite());
                        if(areaId!=0)
                            service.setArea(ejbAreaManager.find(areaId));
                        CategoriaServicio serviceCategorie=ejbServiceCategorieManager.find(serviceCategorieId);
                        service.setServiceCategorie(serviceCategorie);
                        service.setCategorie(serviceCategorie.getCategorie());
                        ejbServiceManager.create(service);
                        FacesMessage msg = new FacesMessage("Your post has been successfully registered.");
                        FacesContext.getCurrentInstance().addMessage(null, msg);
                        FacesMessage msg1 = new FacesMessage("The User Account from this email "+userAccount.getEmail()+" exist.");
                        FacesContext.getCurrentInstance().addMessage(null, msg1);
                        FacesMessage msg2 = new FacesMessage("If you forgot your password or need to reactive your account clik in the link to recovery password.");
                        FacesContext.getCurrentInstance().addMessage(null, msg2);
                        FacesMessage msg3 = new FacesMessage("Please enter in your account and published your posting.");
                        FacesContext.getCurrentInstance().addMessage(null, msg3);
                        linkRPOk=true;
                        createOk=true;
                        return "success";
                    }
                    //userAccount.setDefaultSite(sessionBean.getEjbSession().getCurrentSite());
                    userAccount.setRegisterDate(new Date(System.currentTimeMillis()));
                    Random r = new Random();
                    String token = Long.toString(Math.abs(r.nextLong()), 36);
                    userAccount.setConfirmationCode(token);
                    ejbUserManager.update(userAccount, false);
                    ejbEmail.sendAccountConfirmation(userAccount);
                    service.setUser(userAccount);
                }
                else{
                    RegisterUser registerUser = new RegisterUser();
                    registerUser.setEmail(service.getEmail());
                    //registerUser.setDefaultSite(sessionBean.getEjbSession().getCurrentSite());
                    registerUser.setNumberOfPostings(50);
                    registerUser.setRegisterDate(new Date(System.currentTimeMillis()));
                    registerUser.setStatus("pending");
                    Random r = new Random();
                    String token = Long.toString(Math.abs(r.nextLong()), 36);
                    registerUser.setConfirmationCode(token);
                    ejbUserManager.create(registerUser);
                    RegisterUser newRegisterUser = ejbUserManager.merge(registerUser);
                    ejbEmail.sendAccountConfirmation(newRegisterUser);
                    service.setUser(newRegisterUser);
                }
                service.setCode((ejbServiceManager.lastCode())+1);
                service.setType("service");
                service.setStatus("pending");
                service.setCreateDate(new Date(System.currentTimeMillis()));
                service.setSite(sessionBean.getEjbSession().getCurrentSite());
                if(areaId!=0)
                    service.setArea(ejbAreaManager.find(areaId));
                CategoriaServicio serviceCategorie=ejbServiceCategorieManager.find(serviceCategorieId);
                service.setServiceCategorie(serviceCategorie);
                service.setCategorie(serviceCategorie.getCategorie());
                ejbServiceManager.create(service);
                FacesMessage msg = new FacesMessage("Your post has been successfully registered.");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                FacesMessage msg1 = new FacesMessage("For Administrate your Post eez2find creates an Account for you using the email address "+service.getEmail()+" to reply this post.");
                FacesContext.getCurrentInstance().addMessage(null, msg1);
                FacesMessage msg2 = new FacesMessage("Please active your account from email received and published your posting.");
                FacesContext.getCurrentInstance().addMessage(null, msg2);
                createOk=true;
                return "success";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            FacesMessage msg = new FacesMessage("Error your Post can't register, maybe the email could not be sent or it doesn't exist");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return null;
        }
        }
    }
    public String previewCreate(){
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
        HttpSession session = request.getSession();
        if (session.isNew()) {
          try {
            String errorPageURL = externalContext.getRequestContextPath() + "/faces/servicePosting/create.jsp";
            externalContext.redirect(errorPageURL);
            FacesMessage msg = new FacesMessage("The session has bean expired");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return null;
          } catch(IOException ioe) {
            ioe.printStackTrace();
            return null;
          }
        } else {
        SessionBean sessionBean=(SessionBean) SessionContext.getAttribute("sessionBean");
        if(sessionBean.getEjbSession().getOwner()!=null){
            service.setEmail(sessionBean.getEjbSession().getOwner().getEmail());
        return "success";
        }
        else{
            if ((service.getEmail().length() < 4) || !service.getEmail().contains("@") || !service.getEmail().contains(".") || (email1.length() < 4) || !email1.contains("@") || !email1.contains(".") || !service.getEmail().equals(email1)) {
                FacesMessage msg = new FacesMessage("The emails address don't equals or invalids");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return null;
            }
            return "success";
        }
        }
    }
    
    public String update(){
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
        HttpSession session = request.getSession();
        if (session.isNew()) {
          try {
            String errorPageURL = externalContext.getRequestContextPath() + "/faces/welcome.jsp";
            externalContext.redirect(errorPageURL);
            FacesMessage msg = new FacesMessage("The session has bean expired");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return null;
          } catch(IOException ioe) {
            ioe.printStackTrace();
            return null;
          }
        } else {
        try {
            SessionBean sessionBean=(SessionBean) SessionContext.getAttribute("sessionBean");
            if(service.getTypeReplyTo().equals("masked email") && !maskedEmail)
                ejbEmail.addAnonymousEmail("service", service.getCode(), service.getEmail());
            if(!service.getTypeReplyTo().equals("masked email") && maskedEmail)
                ejbEmail.deleteAnonymousEmail("service", service.getCode(), service.getEmail());
            if(areaId!=0)
                service.setArea(ejbAreaManager.find(areaId));
            else
                service.setArea(null);
            CategoriaServicio serviceCategorie=ejbServiceCategorieManager.find(serviceCategorieId);
            service.setServiceCategorie(serviceCategorie);
            service.setCategorie(serviceCategorie.getCategorie());
            ejbServiceManager.update(service);
            FacesMessage msg = new FacesMessage("Successful edit your Post");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            sessionBean.getEjbSession().setService(null);
            SessionContext.removeAttribute("serviceBean");
            return "success";
        } catch (Exception ex) {
            ex.printStackTrace();
            FacesMessage msg = new FacesMessage("Error your Post can't edit");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return null;
        }
        }
    }

    public long getAreaId() {
        return areaId;
    }

    public void setAreaId(long areaId) {
        this.areaId = areaId;
    }
    
    public Area getArea(){
        return ejbAreaManager.find(areaId);
    }

    public List<Location> getLocationsServiceArea(){
        try{
            return ejbLocationManager.locationsArea(ejbAreaManager.find(areaId));
        }catch(Exception ex){
            return new ArrayList<Location>();
        }
    }
    
    public boolean isCreateOk() {
        return createOk;
    }

    public void setCreateOk(boolean createOk) {
        this.createOk = createOk;
    }

    public boolean isLinkRPOk() {
        return linkRPOk;
    }

    public void setLinkRPOk(boolean linkRPOk) {
        this.linkRPOk = linkRPOk;
    }
    
    public String homeUser(){
        SessionContext.removeAttribute("serviceBean");
        return "homeUser";
    }
    
    public int getBack() {
        return back;
    }

    public void setBack(int back) {
        this.back = back;
    }

    public long getServiceCategorieId() {
        if(serviceCategorieId==0){
            try{
            PostBean postBean=(PostBean) RequestContext.getAttribute("postBean");
            serviceCategorieId=postBean.getCategorieId();
            }catch(Exception ex){}
        }
        return serviceCategorieId;
    }

    public void setServiceCategorieId(long serviceCategorieId) {
        this.serviceCategorieId = serviceCategorieId;
    }

    public List<Service> getListServices(){
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
        HttpSession session = request.getSession();
        if (session.isNew()) {
          try {
            String errorPageURL = externalContext.getRequestContextPath() + "/faces/servicePosting/list.jsp";
            externalContext.redirect(errorPageURL);
            FacesMessage msg = new FacesMessage("The session has bean expired");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return null;
          } catch(IOException ioe) {
            ioe.printStackTrace();
            return null;
          }
        } else {
        String consult="";
        boolean serviceC=false;
        if(serviceCategorieId>0){
            consult=consult+" AND s.serviceCategorie=:serviceCategorie";
            serviceC=true;
        }
        if(hasImage)
            consult=consult+" AND s.description like '%<img src=%'";
        if(searchValue!=null && !searchValue.equals("")){
            if(onlySearchTitles)
                consult=consult+" AND s.title like '%"+searchValue+"%'";
            else
                consult=consult+" AND (s.title like '%"+searchValue+"%' OR s.description like '%"+searchValue+"%')";
        }
        SessionBean sessionBean=(SessionBean) SessionContext.getAttribute("sessionBean");
        if(sessionBean.getEjbSession().getCurrentArea()==null)
            return ejbServiceManager.listServicesSite(sessionBean.getEjbSession().getCurrentSite(), serviceC, ejbServiceCategorieManager.find(serviceCategorieId), consult);
        else
            return ejbServiceManager.listServicesArea(sessionBean.getEjbSession().getCurrentArea(), serviceC, ejbServiceCategorieManager.find(serviceCategorieId), consult);
        }
    }
    
    public String backView(){
        service = null;
        return "backService"+back;
    }
    
    public String backCreate(){
        SessionContext.removeAttribute("serviceBean");
        return "back"+back;
    }
    
    public String backEdit(){
        SessionContext.removeAttribute("serviceBean");
        return "back";
    }

    public String getEmail1() {
        return email1;
    }

    public void setEmail1(String email1) {
        this.email1 = email1;
    }
    
    public Date getToDay(){
        return new Date(System.currentTimeMillis());
    }

    public String getDescription(){
        try{
            if(service.getDescription().contains("\n"))
                return service.getDescription().replaceAll("\n", "<br/>");
            else
                return service.getDescription().replaceAll("\r", "<br/>");
        }catch(Exception ex){
            ex.printStackTrace();
            return "Do not Message";
        }
    }

    public String getSearchValue() {
        if(searchValue==null){
            try {
                PostBean postBean = (PostBean) RequestContext.getAttribute("postBean");
                searchValue = postBean.getSearchValue();
            } catch (Exception ex) {
            }
        }
        return searchValue;
    }

    public void setSearchValue(String searchValue) {
        this.searchValue = searchValue;
    }

    public boolean isOnlySearchTitles() {
        return onlySearchTitles;
    }

    public void setOnlySearchTitles(boolean onlySearchTitles) {
        this.onlySearchTitles = onlySearchTitles;
    }

    public boolean isHasImage() {
        return hasImage;
    }

    public void setHasImage(boolean hasImage) {
        this.hasImage = hasImage;
    }

    public int getPage() {
        if(page==0)
            page=1;
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }
    
    public int getContador(){
        try{
            return 20000-service.getDescription().length();
        }catch(Exception ex){
            return 20000;
        }
    }
    
    public void setContador(int contador){}
    

    public void flaggingMiscategorized(){
        try {
            service.setMiscategorized(ejbServiceManager.merge(service).getMiscategorized()+1);
            ejbServiceManager.update(service);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public void flaggingProhibited(){
        try {
            service.setProhibited(ejbServiceManager.merge(service).getProhibited()+1);
            ejbServiceManager.update(service);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public void flaggingSpam(){
        try {
            service.setSpam(ejbServiceManager.merge(service).getSpam()+1);
            ejbServiceManager.update(service);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public void flaggingBest(){
        try {
            service.setBest(ejbServiceManager.merge(service).getBest()+1);
            ejbServiceManager.update(service);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
